package com.hnkywl.sts.util;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-3-28
 * Time: 下午2:43
 * To change this template use File | Settings | File Templates.
 */
public class ReflectionUtils {
    /**
     * 用于对类的字段赋值，无视private,project修饰符,无视set/get方法
     *
     * @param object    要反射的类
     * @param init 要录入的类
     * @param nonNecessaryFields 不需要修改的字段
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Object getInstance(Object object, Object init,String[] nonNecessaryFields) {
        try {
           // Object object = Class.forName(c.getName()).newInstance();
            Class<?> obj = object.getClass();
            Class<?> superObj=obj.getSuperclass();

            Field[] fields = obj.getDeclaredFields();
            Field[] superFields=superObj.getDeclaredFields();

            Field[] initFields=init.getClass().getDeclaredFields();
            Field[] initSuperFields=init.getClass().getSuperclass().getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {
                initFields[i].setAccessible(true);
                if(!Arrays.asList(nonNecessaryFields).contains(initFields[i].getName())/* || initFields[i].get(init)!=null*/){
                    fields[i].setAccessible(true);
                    fields[i].set(object,initFields[i].get(init));
                }
            }

            for (int i = 0; i < superFields.length; i++) {
                initSuperFields[i].setAccessible(true);
                if(!Arrays.asList(nonNecessaryFields).contains(initSuperFields[i].getName())/* || initSuperFields[i].get(init)!=null*/){
                    superFields[i].setAccessible(true);
                    superFields[i].set(object,initSuperFields[i].get(init));
                }
            }
            return object;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getInstance(Object object, Object init){
        return getInstance(object,init,new String[]{"htwb","deleted","dateCreated","lastUpdated","createUser","createOrgan","createDepartment"});
    }
}
